﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SQLite;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WindowsFormsApp1
{
    public class SqlLiteLongConn
    {
        //数据库连接字符串(web.config来配置)，可以动态更改connectionString支持多数据库.           
        public static string connectionString = "Data Source=" + Path.Combine(System.Windows.Forms.Application.StartupPath, "resume.sqlite");
        #region 使用长连接处理
        public static SQLiteConnection _connection;
        public static void OpenConnection()
        {
            if (_connection == null || _connection.State == ConnectionState.Closed)
                _connection = new SQLiteConnection(connectionString);
            if (_connection.State != ConnectionState.Open)
                _connection.Open();
        }

        public static void CloseConnecton()
        {
            if (_connection != null)
                _connection.Close();

        }


        #endregion

        /// <summary>  
        /// 执行SQL语句，返回影响的记录数  
        /// </summary>  
        /// <param name="SQLString">SQL语句</param>  
        /// <returns>影响的记录数</returns>  
        public static int ExecuteSql(string SQLString)
        {
            OpenConnection();
            using (SQLiteCommand cmd = new SQLiteCommand(SQLString, _connection))
            {
                try
                {
                    int rows = cmd.ExecuteNonQuery();
                    return rows;
                }
                catch (System.Data.SQLite.SQLiteException E)
                {
                    throw E;
                    //return 0;
                }
            }
        }

        /// <summary>  
        /// 执行查询语句，返回DataSet  
        /// </summary>  
        /// <param name="SQLString">查询语句</param>  
        /// <returns>DataSet</returns>  
        public static DataSet Query(string SQLString)
        {
            OpenConnection();
            DataSet ds = new DataSet();
            try
            {
                using (SQLiteDataAdapter command = new SQLiteDataAdapter(SQLString, _connection))
                {
                    command.Fill(ds, "ds");
                }
            }
            catch (System.Data.SQLite.SQLiteException ex)
            {
                throw ex;
            }

            return ds;

        }


    }
}
